package com.xdja;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.*;
import io.netty.handler.proxy.HttpProxyHandler;
import io.netty.handler.proxy.ProxyConnectionEvent;
import io.netty.util.AttributeKey;
import io.netty.util.ReferenceCountUtil;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * description
 *
 * @author zk
 * @since 2018/9/25
 */
public class ClientStart {

    public static void main(String[] args) throws InterruptedException {
        AttributeKey<Channel> proxyChannelKey = AttributeKey.valueOf("proxyChannel");

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(new NioEventLoopGroup(),new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                String hostLine = ((ByteBuf)msg).toString(Charset.forName("UTF-8"));
                                String hostNameWithPort = hostLine.substring(hostLine.indexOf(" ") + 1,hostLine.indexOf(" ",hostLine.indexOf(" ") + 1));
                                if(hostNameWithPort.startsWith("http://")){
                                    hostNameWithPort = hostNameWithPort.substring(7);
                                } else if (hostNameWithPort.startsWith("https://")){
                                    hostNameWithPort = hostNameWithPort.substring(8);
                                }
                                String hostName = hostNameWithPort.contains(":") ? hostNameWithPort.substring(0,hostNameWithPort.indexOf(":")) : hostNameWithPort;
                                String port = hostNameWithPort.contains(":") ? hostNameWithPort.substring(hostNameWithPort.indexOf(":") + 1) : "80";
                                initProxyConnection(ctx.channel(), proxyChannelKey,new InetSocketAddress(hostName,Integer.valueOf(port)));
                                ctx.channel().writeAndFlush(ctx.alloc().buffer().writeBytes(new byte[]{72,84,84,80,47,49,46,49,32,50,48,48,32,79,75,13,10,13,10}));
                                ctx.pipeline().remove(this);
                                ReferenceCountUtil.release(msg);
                            }
                        })
                                .addLast(new HttpServerCodec())
                                .addLast(new HttpObjectAggregator(1024 * 3))
                                .addLast(new MessageToMessageDecoder() {
                                    @Override
                                    protected void decode(ChannelHandlerContext ctx, Object msg, List out) throws Exception {
                                        Channel remoteChannel = ctx.channel().attr(proxyChannelKey).get();
                                        if(remoteChannel == null){
                                            System.out.println("wait remoteChannel pre");
                                            return;
                                        } else {
                                            remoteChannel.writeAndFlush(msg);
                                        }
                                    }
                        });
                    }
                });
        ChannelFuture future = serverBootstrap.bind(8989);
        future.channel().closeFuture().sync();
    }

    public static void initProxyConnection(Channel clientChannel,AttributeKey<Channel> proxyChannel,InetSocketAddress destinationAddress) throws InterruptedException {
        InetSocketAddress remoteAddress = new InetSocketAddress("127.0.0.1",1080);
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(new HttpProxyHandler(remoteAddress))
                                .addLast(new ChannelInboundHandlerAdapter(){
                                    @Override
                                    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                                        if(evt instanceof ProxyConnectionEvent){
                                            System.out.println("handShake is success.");
                                            ctx.pipeline().remove(HttpClientCodec.class);//remove unUse http handler
                                            ctx.pipeline().remove(HttpProxyHandler.class);//remove unUse http handler
                                            ctx.pipeline()
                                                    .addLast(new SimpleChannelInboundHandler<ByteBuf>() {
                                                        @Override
                                                        protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
                                                            System.out.println(" i think you should debug here");
                                                            clientChannel.writeAndFlush(msg.retain());
                                                        }
                                            });
                                        } else {
                                            ctx.fireUserEventTriggered(evt);
                                        }
                                    }
                                });
                    }
                });
        bootstrap.connect(destinationAddress).sync().addListener((ChannelFutureListener) future -> {
            if(future.isSuccess()){
                System.out.printf("-------->client {%s} set proxyChannel\n",clientChannel.id());
                clientChannel.attr(proxyChannel).set(future.channel());
            } else {
                System.out.println("httpProxy set fail");
            }
        });
    }
}